package com.kyc.kycxkplaygame.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.alipay.sdk.app.PayTask;
import com.kyc.kycxkplaygame.R;
import com.kyc.kycxkplaygame.alipay.AuthResult;
import com.kyc.kycxkplaygame.alipay.OrderInfoUtil2_0;
import com.kyc.kycxkplaygame.alipay.PayResult;
import com.kyc.kycxkplaygame.dbutils.GetPropLevelUtils;
import com.kyc.kycxkplaygame.dbutils.IntImp.AlasbusyIApi;
import com.kyc.kycxkplaygame.dbutils.inter.HttpQuestResultListener;
import com.kyc.kycxkplaygame.entity.PropsCode;
import com.kyc.kycxkplaygame.util.ConstactUtil;
import com.kyc.kycxkplaygame.util.TimeUtil;
import com.kyc.kycxkplaygame.util.getTiliTimeUtils;
import es.dmoral.toasty.Toasty;

import java.util.Map;

import static com.kyc.kycxkplaygame.util.ConstactUtil.*;

public class UseAndBuyTiliActivity extends Activity implements HttpQuestResultListener {

    private ImageView add_tili_count;
    private TextView add_tili_daojishi;
    private ImageView buy_tili_btn;
    private ImageView add_eat_xiyou;
    private TextView xiyou_num;
    private ImageView add_eat_caomei;
    private TextView caomei_num;
    private ImageView add_eat_putao;
    private TextView putao_num;
    private int xiyou;
    private int apple;
    private int xigua;
    private String tili_num;
    private ImageView add_tili_huifu_tishi;
    private ImageView add_tili_full_tishi;

    String propName = "";

    private int second = 60;
    private int min = 5;

    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ConstactUtil.SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    Log.i("TAG", "resultStatus === " + resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(UseAndBuyTiliActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        if (TextUtils.isEmpty(propName)) {
                            alasbusyIApi.insertProps(GetPropLevelUtils.getInstance().getUserName(), "体力", 5);
                        } else {
                            alasbusyIApi.insertProps(GetPropLevelUtils.getInstance().getUserName(), propName, 1);
                        }
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(UseAndBuyTiliActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                        //onBackPressed();
                    }
                    break;
                }
                case ConstactUtil.SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(UseAndBuyTiliActivity.this,
                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(UseAndBuyTiliActivity.this,
                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();
                        //onBackPressed();

                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };
    private AlasbusyIApi alasbusyIApi;

    private int num = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setFinishOnTouchOutside(false);
        setContentView(R.layout.activity_use_and_buy_tili);
        Window window = getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.alpha = 1f;
        window.setAttributes(layoutParams);

        Intent intent = getIntent();
        xiyou = intent.getIntExtra("xiyou", 0);
        apple = intent.getIntExtra("apple", 0);
        xigua = intent.getIntExtra("xigua", 0);
        tili_num = intent.getStringExtra("tili_num");
        num = Integer.parseInt(tili_num);
        initView();
    }

    private void initView() {
        add_tili_count = findViewById(R.id.add_tili_count);
        add_tili_daojishi = findViewById(R.id.add_tili_daojishi);
        buy_tili_btn = findViewById(R.id.buy_tili_btn);

        add_tili_huifu_tishi = findViewById(R.id.add_tili_huifu_tishi);
        add_tili_full_tishi = findViewById(R.id.add_tili_full_tishi);

        add_eat_xiyou = findViewById(R.id.add_eat_xiyou);
        xiyou_num = findViewById(R.id.xiyou_num);

        add_eat_caomei = findViewById(R.id.add_eat_caomei);
        caomei_num = findViewById(R.id.caomei_num);

        add_eat_putao = findViewById(R.id.add_eat_putao);
        putao_num = findViewById(R.id.putao_num);

        if (Integer.parseInt(tili_num) == 0) {
            add_tili_count.setImageResource(R.drawable.add_tili_0);
            min = min * 5 - getTiliTimeUtils.getTimeMin(this);
            second = second - getTiliTimeUtils.getTimeSecond(this);
            add_tili_daojishi.setText("00:" + min + ":" + second);
            mHandler.postDelayed(timeFullRunnabale, 1000);
        } else if (Integer.parseInt(tili_num) == 1) {
            add_tili_count.setImageResource(R.drawable.add_tili_1);
            buy_tili_btn.setImageResource(R.drawable.add_tili_buy_btn_4);
            min = min * 4 - getTiliTimeUtils.getTimeMin(this);
            second = second - getTiliTimeUtils.getTimeSecond(this);
            add_tili_daojishi.setText("00:" + min + ":" + second);
            mHandler.postDelayed(timeFullRunnabale, 1000);
        } else if (Integer.parseInt(tili_num) == 2) {
            add_tili_count.setImageResource(R.drawable.add_tili_2);
            buy_tili_btn.setImageResource(R.drawable.add_tili_buy_btn_3);
            min = min * 3 - getTiliTimeUtils.getTimeMin(this);
            second = second - getTiliTimeUtils.getTimeSecond(this);
            add_tili_daojishi.setText("00:" + min + ":" + second);
            mHandler.postDelayed(timeFullRunnabale, 1000);
        } else if (Integer.parseInt(tili_num) == 3) {
            add_tili_count.setImageResource(R.drawable.add_tili_3);
            buy_tili_btn.setImageResource(R.drawable.add_tili_buy_btn_2);
            min = min * 2 - getTiliTimeUtils.getTimeMin(this);
            second = second - getTiliTimeUtils.getTimeSecond(this);
            add_tili_daojishi.setText("00:" + min + ":" + second);
            mHandler.postDelayed(timeFullRunnabale, 1000);
        } else if (Integer.parseInt(tili_num) == 4) {
            second = second - getTiliTimeUtils.getTimeSecond(this);
            add_tili_count.setImageResource(R.drawable.add_tili_4);
            buy_tili_btn.setImageResource(R.drawable.add_tili_buy_btn_1);
            add_tili_daojishi.setText("00:" + (min - getTiliTimeUtils.getTimeMin(this)) + ":" + second);
            mHandler.postDelayed(timeFullRunnabale, 1000);
        } else if (Integer.parseInt(tili_num) == 5) {
            add_tili_count.setImageResource(R.drawable.add_tili_5);
            add_tili_daojishi.setVisibility(View.INVISIBLE);
            add_tili_huifu_tishi.setVisibility(View.GONE);
            add_tili_full_tishi.setVisibility(View.VISIBLE);
            buy_tili_btn.setImageResource(R.drawable.add_tili_jixu_game);
        }

        if (xiyou > 0) {
            xiyou_num.setVisibility(View.VISIBLE);
            xiyou_num.setText("" + xiyou);
        } else {
            add_eat_xiyou.setImageResource(R.drawable.add_tili_xiyou_buy);
        }

        if (apple > 0) {
            caomei_num.setVisibility(View.VISIBLE);
            caomei_num.setText("" + apple);
        } else {
            add_eat_caomei.setImageResource(R.drawable.add_tili_apple_buy);
        }

        if (xigua > 0) {
            putao_num.setVisibility(View.VISIBLE);
            putao_num.setText("" + xigua);
        } else {
            add_eat_putao.setImageResource(R.drawable.add_tili_xigua_buy);
        }

        findViewById(R.id.add_tili_delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UseAndBuyTiliActivity.this.finish();
            }
        });

        buy_tili_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                propName = "";
                if (Integer.parseInt(tili_num) == 5) {
                    UseAndBuyTiliActivity.this.finish();
                } else if (Integer.parseInt(tili_num) == 4) {
                    payV2(0.7, "补满体力");
                } else if (Integer.parseInt(tili_num) == 3) {
                    payV2(1.4, "补满体力");
                } else if (Integer.parseInt(tili_num) == 2) {
                    payV2(2.1, "补满体力");
                } else if (Integer.parseInt(tili_num) == 1) {
                    payV2(2.8, "补满体力");
                } else if (Integer.parseInt(tili_num) == 0) {
                    payV2(3.5, "补满体力");
                }
            }
        });

        findViewById(R.id.xiyou_linlayout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (xiyou_num.getVisibility() == View.INVISIBLE) {
                    propName = "西柚道具";
                    payV2(0.7, propName);
                } else {
                    //直接使用道具
                    if (Integer.parseInt(tili_num) >= 5) {
                        return;
                    } else {
                        if (num < 5) {
                            num += 1;
                            alasbusyIApi.insertProps(GetPropLevelUtils.getInstance().getUserName(), "体力", num);
                            alasbusyIApi.insertProps(GetPropLevelUtils.getInstance().getUserName(), "西柚", Integer.parseInt(xiyou_num.getText().toString()) - 1);
                            GetPropLevelUtils.getInstance().updatePropNum("体力", num);
                        } else {
                            Toasty.warning(UseAndBuyTiliActivity.this, "体力已满,马上去闯关吧.").show();
                            return;
                        }
                    }
                }
            }
        });
        findViewById(R.id.apple_linlayout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (caomei_num.getVisibility() == View.INVISIBLE) {
                    propName = "青苹果道具";
                    payV2(1.4, propName);
                } else {
                    if (Integer.parseInt(tili_num) >= 5) {
                        return;
                    } else {
                        if (num < 5) {
                            num += 2;
                            if (num > 5) {
                               num = 5;
                            }
                            alasbusyIApi.insertProps(GetPropLevelUtils.getInstance().getUserName(), "体力", num);
                            alasbusyIApi.insertProps(GetPropLevelUtils.getInstance().getUserName(), "青苹果", Integer.parseInt(caomei_num.getText().toString()) - 1);
                            GetPropLevelUtils.getInstance().updatePropNum("体力", num);
                        } else {
                            Toasty.warning(UseAndBuyTiliActivity.this, "体力已满,马上去闯关吧.").show();
                            return;
                        }
                    }
                }
            }
        });
        findViewById(R.id.xigua_linlayout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (putao_num.getVisibility() == View.INVISIBLE) {
                    propName = "西瓜道具";
                    payV2(3.5, propName);
                } else {
                    if (Integer.parseInt(tili_num) >= 5) {
                        return;
                    } else {
                        if (num < 5) {
                            num += 5;
                            if (num > 5) {
                                num = 5;
                            }
                            alasbusyIApi.insertProps(GetPropLevelUtils.getInstance().getUserName(), "体力", num);
                            alasbusyIApi.insertProps(GetPropLevelUtils.getInstance().getUserName(), "青苹果", Integer.parseInt(putao_num.getText().toString()) - 1);
                            GetPropLevelUtils.getInstance().updatePropNum("体力", num);
                        } else {
                            Toasty.warning(UseAndBuyTiliActivity.this, "体力已满,马上去闯关吧.").show();
                            return;
                        }
                    }
                }
            }
        });

        alasbusyIApi = AlasbusyIApi.getInstance(this);
        alasbusyIApi.setHttpQuestResultListener(this);
    }

    public void sendusePropBroad() {
        new Thread() {
            @Override
            public void run() {
                Intent intent = new Intent(ConstactUtil.UseTiliProp);
                intent.putExtra("num",num);
                sendBroadcast(intent);
            }
        }.start();

    }

    Runnable timeFullRunnabale = new Runnable() {
        @Override
        public void run() {
            if (second > 0) {
                second = second - 1;
            } else if (second == 0) {
                second = 60;
                min = min - 1;
                if (min == 20 && second <= 60) {
                    add_tili_count.setImageResource(R.drawable.add_tili_1);
                } else if (min == 15 && second <= 60) {
                    add_tili_count.setImageResource(R.drawable.add_tili_2);
                } else if (min == 10 && second <= 60) {
                    add_tili_count.setImageResource(R.drawable.add_tili_3);
                } else if (min == 5 && second <= 60) {
                    add_tili_count.setImageResource(R.drawable.add_tili_4);
                }
            }
            add_tili_daojishi.setText("00:" + min + ":" + second);
            if (min == 0 && second == 0) {
                add_tili_count.setImageResource(R.drawable.add_tili_5);
                add_tili_daojishi.setVisibility(View.INVISIBLE);
                add_tili_huifu_tishi.setVisibility(View.GONE);
                add_tili_full_tishi.setVisibility(View.VISIBLE);
                buy_tili_btn.setImageResource(R.drawable.add_tili_jixu_game);
                mHandler.removeCallbacks(timeFullRunnabale);
            }
            mHandler.postDelayed(timeFullRunnabale, 1000);
        }
    };

    /**
     * 支付宝支付业务
     */
    public void payV2(double price, String propName) {
        if (TextUtils.isEmpty(ConstactUtil.APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置APPID | RSA_PRIVATE")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialoginterface, int i) {
                            //
                            finish();
                        }
                    }).show();
            return;
        }

        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
       /* PayTask payTask = new PayTask(this);
        String version = payTask.getVersion();*/
        String time = TimeUtil.getNowYMDHMSTime();
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2, price, "游戏道具", propName, time/*,version*/);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(UseAndBuyTiliActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = ConstactUtil.SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @Override
    public void onError(Object e) {

    }

    @Override
    public void onSuccess(Object object) {
        if (object instanceof PropsCode) {
            PropsCode propsCode = (PropsCode) object;
            if (propsCode.getCode() == 200) {
                Log.i("KYCC", propsCode.getMessage());
                sendusePropBroad();
            }
        }
    }

    @Override
    public void onQuestErroCode(Object object) {
        if (object instanceof PropsCode) {
            PropsCode propsCode = (PropsCode) object;
        }
    }
}
